import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import Input from '@/components/Input/index';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import { Toast } from 'antd-mobile';
import { useDispatch } from 'react-redux';
import { authorizations, sendCode } from './../../store/action/user';
import { useEffect, useRef, useState } from 'react';
import { useHistory } from 'react-router-dom';

export default function Login() {
  const dispatch = useDispatch();

  const history = useHistory();
  const formlk = useFormik({
    initialValues: {
      mobile: '13566667777',
      code: '',
    },
    onSubmit: async (values) => {
      await dispatch(authorizations(values));

      Toast.show({ content: '登录成功' });

      history.push('/');
    },

    validationSchema: Yup.object().shape({
      mobile: Yup.string()
        .required('手机号不能为空')
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}/, '验证码格式错误'),
    }),
  });

  const [second, setSecond] = useState(0);

  const timerIdRef = useRef(-1);
  const handleSendCode = async () => {
    if (formlk.errors.mobile) return Toast.show({ content: formlk.errors.mobile });
    await dispatch(sendCode(formlk.values.mobile));
    Toast.show({ content: '验证码发送成功' });
    setSecond(60);

    timerIdRef.current = window.setInterval(() => {
      setSecond((preSecond) => {
        if (preSecond === 1) clearInterval(timerIdRef.current);
        return preSecond - 1;
      });
    }, 1000);
  };

  useEffect(() => {
    return () => clearInterval(timerIdRef.current);
  }, []);

  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        <h3>短信登录</h3>
        <form onSubmit={formlk.handleSubmit}>
          <div className="input-item">
            <Input
              placeholder="请输入手机号"
              autoFocus
              autoComplete="off"
              type="text"
              name="mobile"
              maxLength={11}
              value={formlk.values.mobile}
              onChange={formlk.handleChange}
              onBlur={formlk.handleBlur}
              errorMsg={formlk.touched.mobile ? formlk.errors.mobile : ''}
            />
          </div>

          <div className="input-item">
            <Input
              extra={
                !second ? (
                  <span onClick={handleSendCode}>获取验证码</span>
                ) : (
                  <span>{second}秒后再发送</span>
                )
              }
              className="input"
              placeholder="请输入验证码"
              autoComplete="off"
              type="text"
              name="code"
              maxLength={6}
              value={formlk.values.code}
              onChange={formlk.handleChange}
              onBlur={formlk.handleBlur}
              errorMsg={formlk.touched.code ? formlk.errors.code : ''}
            />
          </div>
          <button type="submit" className="login-btn" disabled={!formlk.isValid}>
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
